import Vue from 'vue'
import VueRouter from 'vue-router'
import MainView from "@/views/MainView.vue";
import FlowerView from "@/views/FlowerView.vue";
import OrderView from "@/views/OrderView.vue";
import AccountView from "@/views/AccountView.vue";
import CommentView from "@/views/CommentView.vue";
import IndexView from "@/views/IndexView.vue";
import OrderItemView from "@/views/OrderItemView.vue";
import SelfView from "@/views/SelfView.vue";
import LoginView from "@/views/LoginView.vue";
import {Message} from "element-ui";



Vue.use(VueRouter)

const routes = [
  { path: '/main', name: 'MainView', component: MainView,
    children: [
      { path: '/index', name: 'IndexView', component:IndexView },
      { path: '/flower', name: 'FlowerView', component:FlowerView  },
      { path: '/order', name: 'OrderView', component:OrderView,},
      {path: '/orderitem', name: 'OrderItemView', component: OrderItemView,},
      { path: '/account', name: 'AccountView', component:AccountView },
      { path: '/comment', name: 'CommentView', component:CommentView },
      { path: '/self', name: 'SelfView', component:SelfView },
    ],
  },
  {
    path: '/',
    name: 'LoginView',
    component: LoginView
  },
]



const router = new VueRouter({
  routes
})

//添加路由守卫
router.beforeEach(async (to, from, next) => {
  // 按官网提供的示例，做修改
  let token = sessionStorage.getItem("token");
  console.log(token)
  console.log("上一个视图",  from )
  console.log("要访问的视图名：" + to.name)
  if (token == null && to.name != 'LoginView') {
    console.log("---- 前端守卫，拦截没有登录 ----")
    Message({
      type: "error",
      message: "对不起，请先登录",
      duration: 1000
    })
    // 将用户重定向到登录页面
    return {name: 'LoginView'}
  }
  next();
})



export default router
